<template>
  <el-card style="margin: 30px 0px">
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input
          placeholder="请输入SPU名称"
          v-model="spuInfo.spuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spuInfo.tmId" placeholder="选择品牌">
          <el-option
            :label="trade.tmName"
            :value="trade.id"
            :key="trade.id"
            v-for="trade in trademarkArr"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          placeholder="请输入描述"
          type="textarea"
          v-model="spuInfo.description"
        ></el-input>
      </el-form-item>

      <el-form-item label="图片">
        <el-upload
          :on-success="handleAvatarSuccess"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="imgArr"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-select
          v-model="saleIdAndName"
          :placeholder="
            unSelectSalesArr.length
              ? '还剩' + unSelectSalesArr.length + '个'
              : '没有了'
          "
        >
          <el-option
            :label="unSale.name"
            :value="`${unSale.id}:${unSale.name}`"
            :key="unSale.id"
            v-for="unSale in unSelectSalesArr"
          >
          </el-option>
        </el-select>
        <el-button
          style="margin: 0 10px"
          type="primary"
          icon="el-icon-plus"
          @click="addSalesAttr"
          :disabled="!saleIdAndName"
          >添加销售属性</el-button
        >

        <el-table
          border
          stripe
          :data="spuInfo.spuSaleAttrList"
          style="width: 100%; margin: 10px 0"
        >
          <el-table-column type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column label="属性名" width="80" prop="saleAttrName">
          </el-table-column>
          <el-table-column label="属性值列表" width="with">
            <template slot-scope="{ row,$index}">
              <el-tag
                :key="tag.id"
                v-for="(tag,index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index,1)">
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.showInput"
                v-model="row.inputValue"
                @blur="blurHandle(row)"
                @keyup.native.enter="blurHandle(row)"
                ref="cur"
                size="small"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >+ 添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80"> 
            <template slot-scope="{row,$index}">
              <el-button type="primary" icon="el-icon-delete" @click="spuInfo.spuSaleAttrList.splice($index,1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item size="normal">
        <el-button type="primary" size="default" icon="el-icon-date"
        @click="save"
          >保存</el-button
        >
        <el-button size="default" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "AddSpu",
  data() {
    return {
      saleIdAndName: "",
      city: "",
      dialogImageUrl: "",
      dialogVisible: false,
      spuInfo: {
        category3Id: "",
        spuName: "",
        tmId: "",
        description: "",
        spuImageList: [
          // {
          //   imgName: "",
          //   imgUrl: "",
          // },
        ],
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: "", //销售属性的ID
          //   saleAttrName: "", //销售属性的名称
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: "",
          //       saleAttrValueName: "",
          //     },
          //   ],
          // },
        ],
      },
      //某一个SPU照片墙的数据
      imgArr: [],
      //品牌的数据
      trademarkArr: [],
      //全部的销售属性
      allSaleAttr: [],
    };
  },
  computed: {
    unSelectSalesArr() {
      return this.allSaleAttr.filter((item) => {
        return this.spuInfo.spuSaleAttrList.every(
          (item1) => item1.baseSaleAttrId != item.id
        );
      });
    },
  },
  methods: {
    cancel(){
      this.$emit('changeScene')
      
      Object.assign(this._data,this.$options.data())
    },

    async init(c3){
      this.spuInfo.category3Id = c3
      let p1 = this.$http.spu.reqTradeMark();
      let p2 = this.$http.spu.reqAllSaleAttr();
      let res = await Promise.all([p1, p2]);
       this.trademarkArr = res[0].data;
      this.allSaleAttr = res[1].data;
    },
      //保存业务
    async save() {
      // console.log(this.imgArr);
      //整理参数
      //图片的参数
      this.spuInfo.spuImageList = this.imgArr.map((item) => {
        return {
          imgName: item.name,
          //分情况
          imgUrl: (item.response && item.response.data) || item.url,
        };
      });

      try {
        //发请求进行修改或者是添加
        await this.$http.spu.reqAddOrUpdateSpu(this.spuInfo);
        this.$message({type:'success',message:this.spuInfo.id?'修改成功':'添加成功'});
        //通知父组件切换场景
        this.$emit('changeScene',this.spuInfo.id?true:false);
        Object.assign(this._data,this.$options.data())

      } catch (error) {

      }
    },
    blurHandle(row) {
      if(row.inputValue.trim()==''){
        return this.$message({
          type:'error',
          message:'不能为空'
        })
      }

      if(row.spuSaleAttrValueList.find(item=>item.saleAttrValueName == row.inputValue)){
        return this.$message({
          type:'error',
          message:'有重复的值'
        })
      }
      let newValue = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue,
      };
      row.spuSaleAttrValueList.push(newValue);
      row.showInput = false;
    },
    addSaleAttrValue(row) {
      this.$set(row, "showInput", true);
      this.$set(row, "inputValue", "");
      this.$nextTick(() => {
        // console.log(this.$refs);
        this.$refs.cur.focus();
      });
    },
    addSalesAttr() {
      let [baseSaleAttrId, saleAttrName] = this.saleIdAndName.split(":");
      this.spuInfo.spuSaleAttrList.push({
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      });
      this.saleIdAndName = "";
    },
    handleAvatarSuccess(ren, file, list) {
      // console.log(ren);
      // console.log(file);
      // console.log(list);
      this.imgArr = list;
    },
    async getSpuInfo(spu) {
      // console.log(spu);
      let p1 = this.$http.spu.reqSpuInfo(spu.id);
      let p2 = this.$http.spu.reqSpuImgList(spu.id);
      let p3 = this.$http.spu.reqTradeMark();
      let p4 = this.$http.spu.reqAllSaleAttr();

      let res = await Promise.all([p1, p2, p3, p4]);
      // console.log(res);
      this.spuInfo = res[0].data;
      // console.log(res[1].data);
      this.imgArr = res[1].data.map((item) => ({
        name: item.imgName,
        url: item.imgUrl,
      }));
      this.trademarkArr = res[2].data;
      this.allSaleAttr = res[3].data;
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.imgArr = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>